<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <!-- :immediate-check="false" -->
      <comment-cell :list="list"></comment-cell>
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <!-- <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group> -->
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { getComments } from "@/api/comment";
import commentCell from "./comment_cell.vue";
import eventBus from "@/utlis/bus";
export default {
  name: "ArticleComment",
  components: {
    commentCell,
  },
  props: {
    article_id: {
      type: [Number, String],
      require: true,
    },
    type: {
      type: String,
      require: true,
      default: "a",
    },
  },
  data() {
    return {
      list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null,
    };
  },
  created() {
    if (this.type == "a") {
      // this.loading = true;
      this.onLoad(); //两种方式解决首次加载更多的
    }
    this.updateCommFn();
  },

  methods: {
    async onLoad() {
      try {
        let re = await getComments({
          type: this.type,
          source: this.article_id,
          offset: this.offset,
          limit: 20,
        });
        console.log(re);
        let {
          data: {
            data: { last_id, results, total_count },
          },
        } = re;
        this.offset = last_id;
        this.list.push(...results);
        this.loading = false;
        if (!results.length) {
          this.finished = true;
        }

        // 评论总数
        this.$emit("total_count", total_count);
      } catch (error) {
        console.log(error);
      }
    },
    updateCommFn() {
      eventBus.$on("updataComment", (new_obj) => {
        // 组件复用的问题 --只执行一次/销毁另一个组件
        this.list.unshift(new_obj);
      });
    },
  },
};
</script>

<style scoped lang="less">
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}

.van-list {
  margin-bottom: 45px;
}
</style>